//
//  CYBlackAppImageVC.swift
//  CreditAddressBook
//
//  Created by Lee on 15/7/20.
//  Copyright (c) 2015年 Lee. All rights reserved.
//

import UIKit

class CYBlackAppImageVC: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UISearchBarDelegate {
    
    @IBOutlet weak var headImageView: UIImageView!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var searchBar: UISearchBar!
    @IBOutlet weak var collectionView: UICollectionView!
    
    let CellID:String = "CYBlackAppImageCell"
    let margin:CGFloat = 20
    var cellSize:CGSize = CGSize(width: 0, height: 0)
    
    var person:CYPerson!
    var callRecord:CYCallRecord!
    
    var urls:NSMutableArray! = NSMutableArray()
    var imageViews:NSMutableArray! = NSMutableArray()
    
    var footer:MJRefreshBackNormalFooter!//底部刷新控件
    var page:NSInteger! = 1
    var flag:NSInteger! = 0
    
    var searchText:String!
    
    var baiduImage:LEBaiduImage!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupPerson()
        //加载图片
        MBProgressHUD.showMessage("数据加载中", to: self.view)
        loadImage(name: person.name, page: self.page, flag: 0)
        
        //collectioncell设置
        setupCollectionCell()
        //集成刷新控件
        setupRefreshView();
     
    }
    
    func setupPerson() {
        if (person.person.thumbnail != nil) {
            self.headImageView.image = person.person.thumbnail
        } else {
            self.headImageView.image = UIImage(named: "ic_contact_big_header")
        }
        imageViewLayer(self.headImageView, cornerRadius: 30.0, border:0)
        
        self.nameLabel.text = person.name
        self.searchText = person.name;
    }
    
    /**
    *  flag:0:分词 1：不分词
    */
    func loadImage(name: String, page: NSInteger, flag: NSInteger) {
     
        //360图片
//        CYABTool.imageSelectPageWithKey(name, page: page, flag: flag, success: { (arr:[AnyObject]!) -> Void in
//            MBProgressHUD.hideHUDForView(self.view)
//            
//            let imageViews = NSMutableArray()
//            if (arr == nil) {
//                MBProgressHUD.showError("数据加载错误，请稍后再试")
//                return
//            }
//            for (var i = 0; i < arr.count; i++) {
//                let image = UIImageView(frame: CGRect(origin: CGPointZero, size: self.cellSize))
//                //                image.backgroundColor = UIColor.clearColor()
//                self.imageViewLayer(image, cornerRadius: image.frame.size.height/2, border:1.0)
//                
//                image.setImageWithURL(NSURL(string: arr[i] as! String), placeholderImage: UIImage(named: "ic_contact_big_header"))
//                imageViews.addObject(image)
//            }
//            self.imageViews.addObjectsFromArray(imageViews as [AnyObject])
//            
//            self.urls.addObjectsFromArray(arr)
//            self.collectionView.reloadData()
//            
//            self.page = self.page + 1
//            self.footer.endRefreshing()
//            }) { (NSError) -> Void in
//                MBProgressHUD.hideHUDForView(self.view)
//                self.footer.endRefreshing()
//        }

     
          CYABTool.imageSelectPage(withParams: ["name": CYEscape.escape(with: name), "page": (page), "flag": (flag)], success: { (arr:[Any]!) -> Void in
          
            MBProgressHUD.hide(for: self.view)
            
            let imageViews = NSMutableArray()
            if (arr == nil) {
                MBProgressHUD.showError("数据加载错误，请稍后再试")
                return
            }
          
            for i in 0 ..< arr.count {
                let image = UIImageView(frame: CGRect(origin: CGPoint.zero, size: self.cellSize))
//                image.backgroundColor = UIColor.clearColor()
                self.imageViewLayer(image, cornerRadius: image.frame.size.height/2, border:1.0)
                
                image.sd_setImage(with: URL(string: arr[i] as! String), placeholderImage: UIImage(named: "ic_contact_big_header"))
                imageViews.add(image)
            }
            self.imageViews.addObjects(from: imageViews as [AnyObject])
          
            self.urls.addObjects(from: arr)
            self.collectionView.reloadData()
            
            self.page = self.page + 1
            self.footer.endRefreshing()
            }) { (NSError) -> Void in
                MBProgressHUD.hide(for: self.view)
                self.footer.endRefreshing()
        }
        
        //百度图片
//        let param = LEBaiduImageParam()
//        param.word = name
//        param.page = page
//        if (self.baiduImage != nil) {
//            
//            param.pageSize = self.baiduImage.data.count
//        }
//        
//        CYImageSearch.searchImageFromBaiduWithParams(param, success: { (baiduImage:LEBaiduImage!) -> Void in
//            
//            self.baiduImage = baiduImage
//            
//            let arr:NSArray = baiduImage.data
//            var middleURLs: AnyObject? = arr.valueForKeyPath("middleURL")
//            self.urls.addObjectsFromArray(middleURLs as! [AnyObject])
//            
//            self.collectionView.reloadData()
//            
//            MBProgressHUD.hideHUDForView(self.view)
//            self.page = self.page + 1
//            self.footer.endRefreshing()
//            }) { (error:NSError!) -> Void in
//            
//                MBProgressHUD.hideHUDForView(self.view)
//                self.footer.endRefreshing()
//        }
    }
    
    func setupCollectionCell() {
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(UICollectionViewCell.classForCoder(), forCellWithReuseIdentifier:CellID)
        collectionView.contentInset = UIEdgeInsetsMake(margin, margin, 0, margin)
        
        let layout = UICollectionViewFlowLayout()
        //列数
        let cols:CGFloat = 3
        let width = UIScreen.main.bounds.width
        //cell宽度
        let cellW = (width - 4 * margin)/cols
        // cell的大小
        cellSize = CGSize(width: cellW, height: cellW)
        layout.itemSize = cellSize
        
        self.collectionView.collectionViewLayout = layout
        self.collectionView.alwaysBounceVertical = true
        
        self.searchBar.delegate = self
        
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.urls.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//        let url = self.urls[indexPath.row] as! String
        
        let cell:UICollectionViewCell = self.collectionView.dequeueReusableCell(withReuseIdentifier: CellID, for: indexPath)
        
//        let cell:UICollectionViewCell = self.collectionView.dequeueReusableCellWithReuseIdentifier(CellID, forIndexPath: indexPath) as! UICollectionViewCell
        
        cell.backgroundColor = UIColor.clear
        
        let image = self.imageViews[indexPath.row] as! UIImageView
//        image.le_setImageWithURL(url, placeholderImage: UIImage(named: "ic_contact_big_header"))
        cell.subviews.first?.removeFromSuperview()
        cell.addSubview(image)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let url = self.urls[indexPath.row] as! String
        
        let alertView = CustomIOSAlertView()
//        alertView.delegate = self
        let contentView = UIView(frame: CGRect(x: 0, y: 0, width: 250, height: 200))
        let height = contentView.frame.size.height - 20
        let imageView = UIImageView(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: height, height: height)))
        imageView.center = contentView.center
        imageViewLayer(imageView, cornerRadius: height/2, border:1.0)
//        imageView.le_setImageWithURL(url)
        imageView.sd_setImage(with: URL(string: url))
        contentView.addSubview(imageView)
        
        alertView?.containerView = contentView
        alertView?.buttonTitles = ["取消", "保存"]
        
        alertView?.btnClick(self, complete: { (index:Int32) -> Void in
            print("btn:\(index)")
            if(index == 1) {
                CYABTool.jfshop(withType: "2", success: nil, failure: nil)
                let image = imageView.image
                self.shareAlertView(image: image, url: url as NSString)
            }
        })
        alertView?.show()
        
        self.searchBar.resignFirstResponder()
    }
     
    /**
    *  向TA挑衅view
    */
    func shareAlertView(image: UIImage!, url: NSString!) {

          let alertView = CustomIOSAlertView()

          let viewW = UIScreen.main.bounds.width - 80
          let viewH = viewW * (800/450)
        
//        let arr:NSArray = NSBundle.mainBundle().loadNibNamed("CYTXView", owner: nil, options: nil)
//        let contentView = arr.lastObject as! CYTXView
//        let contentView = NSBundle.mainBundle().loadNibNamed("CYTXView", owner: nil, options: nil).first as! CYTXView
          let contentView = CYXTTXView.tt();
          contentView?.frame = CGRect(x: 0, y: 0, width: viewW, height: viewH)
          contentView?.image = image
          contentView?.name = self.nameLabel.text
          contentView?.backgroundColor = UIColor.red

          alertView?.containerView = contentView
          alertView?.buttonTitles = ["默默保存", "向Ta挑衅"]
     
        alertView?.btnClick(self, complete: { (index:Int32) -> Void in
            print("btn:\(index)")
            if(index == 1) {
                
                let sharImage = CYDialTool.image(from: contentView)
                
                UMSocialSnsService.presentSnsIconSheetView(self, appKey: UMAppkey, shareText: "天下无赖", shareImage: sharImage, shareToSnsNames: nil, delegate: nil)
                UMSocialData.default().extConfig.wxMessageType = UMSocialWXMessageTypeImage
            }
            
            //更新通讯录头像本地数据
            let person = self.person.person
            person?.setImage(image)
            person?.save()
            
            //更新通话记录本地图片存储
            let callrecord = self.callRecord;
            if (callrecord != nil) {
                callrecord?.callHistory.thumbnail = image
                callrecord?.callHistory.update()
            }
            
            self.headImageView.image = image
            NotificationCenter.default.post(name: NSNotification.Name.CYAddressBookChange, object: nil, userInfo: [CYAddressBookImageKey: url, CYAddressBookPhoneKey: self.person.phone])
        })
        alertView?.show()
//        LEAlertView.showAlertViewWithTitles(["1", "2"], iconNames: ["1", "2"]) { (Int) -> Void in
        
//        };
    }
    
    /**
    *  搜索键盘按钮点击
    */
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        
        if ((searchBar.text) != nil) {
            self.searchText = searchBar.text
            self.flag = 1
            MBProgressHUD.showMessage("数据加载中", to: self.view)
            self.urls.removeAllObjects()
            self.imageViews.removeAllObjects()
            loadImage(name: searchBar.text!, page: self.page, flag: 1)
        }
        
        self.searchBar.resignFirstResponder()
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.searchBar.resignFirstResponder()
    }
    
    func imageViewLayer(_ imageView: UIImageView, cornerRadius:CGFloat, border:CGFloat) {
        imageView.layer.cornerRadius = cornerRadius
        imageView.layer.masksToBounds = true
        imageView.layer.borderColor = CYNaviThemeColor.cgColor
        imageView.layer.borderWidth = border
    }
    
    /**
    *  刷新控件
    */
    func setupRefreshView() {
        
        let footer = MJRefreshBackNormalFooter { () -> Void in
            print("进入底部刷新状态")
            self.refreshFooterView()
        }
//        footer.setTitle("上拉加载更多", forState: MJRefreshStateIdle)
        self.footer = footer;
        self.collectionView.mj_footer = footer;
    }
    
    func refreshFooterView() {
        self.loadImage(name: self.searchText, page: self.page, flag: self.flag)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
        //停止下载所有图片
        SDWebImageManager.shared().cancelAll()
        //清除内存中的图片
        SDWebImageManager.shared().imageCache.clearMemory()
        
        self.footer = nil
    }
    
    deinit {
        print("图片搜索销毁")
    }
}
